package com.ruiysoft.controller.statement;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruiysoft.controller.statement.util.StatementUtil;
import com.ruiysoft.controller.statement.vo.StatementBalanceVo;
import com.ruiysoft.controller.statement.vo.StatementDetailVo;
import com.ruiysoft.controller.statement.vo.StatementListVo;
import com.ruiysoft.controller.statement.vo.StatementRecordVo;
import com.ruiysoft.controller.sys.api.SysUserApi;
import com.ruiysoft.entity.statement.StatementShop;
import com.ruiysoft.entity.statement.StatementShopDetail;
import com.ruiysoft.entity.sys.SysMicroShop;
import com.ruiysoft.entity.sys.SysShopPersonnel;
import com.ruiysoft.entity.sys.SysUser;
import com.ruiysoft.pub.consts.EnumUtil;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.pub.entity.PageInfo;
import com.ruiysoft.service.statement.IStatementShopDetailService;
import com.ruiysoft.service.statement.IStatementShopService;
import com.ruiysoft.service.statement.bean.StatementCondition;
import com.ruiysoft.service.statement.consts.StatementStatus;
import com.ruiysoft.service.statement.consts.StatementType;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import com.ruiysoft.util.NumberUtils;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-12-02T10:40:23.351+08:00")

@RestController
public class ShopStatementApiController implements ShopStatementApi {

    private static final Logger log = LoggerFactory.getLogger(ShopStatementApiController.class);

    private final IStatementShopService statementShopService;

    private final IStatementShopDetailService statementShopDetailService;

    private final SysUserApi sysUserApi;

    @org.springframework.beans.factory.annotation.Autowired
    public ShopStatementApiController(IStatementShopService statementShopService, IStatementShopDetailService statementShopDetailService, SysUserApi sysUserApi) {
        this.statementShopService = statementShopService;
        this.statementShopDetailService = statementShopDetailService;
        this.sysUserApi = sysUserApi;
    }

    private Long getShopId() {
        SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
        return shop.getId();
    }
    private Long getUserId() {
        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
        return personnel.getId();
    }
    @Override
    public Result<StatementBalanceVo> shopStatementBalanceGet() {
        Long shopId = getShopId();
        try {
            Long sumBalance = statementShopService.selectSumMoney(new StatementCondition().setShopId(shopId).setFreeze(false));
            Long withdrawable = statementShopService.selectSumMoney(new StatementCondition().setShopId(shopId).setArrivalDateLast(new Date()).setFreeze(false));
            return ResultGenerator.genSuccessResult(new StatementBalanceVo()
                    .balance(sumBalance!=null?NumberUtils.changeF2Y2(sumBalance.toString()):"0")
                    .withdrawable(withdrawable!=null?NumberUtils.changeF2Y2(withdrawable.toString()):"0"));
        } catch (Exception e) {
            log.error("店铺查询余额，可提现余额，shopid--{}",shopId, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<PageInfo<StatementListVo>> shopStatementListGet(@NotNull @ApiParam(value = "分页开始页", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页显示多少条数据", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize) {
        Long shopId = getShopId();
        try {
            IPage<StatementShop> page = statementShopService.page(new Page<>(pageStart,pageSize),
                    new QueryWrapper<StatementShop>().eq("shop_id",shopId).orderByDesc("trade_date"));

            List<StatementListVo> list = page.getRecords().stream().map(statement ->
                new StatementListVo().id(statement.getId())
                        .money(statement.getMoney()!=null?NumberUtils.changeF2Y2(statement.getMoney().toString()):"0")
                        .summary(statement.getSummary())
                        .type(statement.getType())
                        .isArrival(StatementUtil.getStatus(statement))
                        .date(statement.getTradeDate() != null ? statement.getTradeDate().getTime() : null)
            ).collect(Collectors.toList());
            return ResultGenerator.genSuccessResult(new PageInfo<StatementListVo>(list, (Page) page));
        } catch (Exception e) {
            log.error("店铺查询收入支出列表，shopid--{}--pageStart--{}--pageSize--{}",shopId,pageStart,pageSize, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }


    @Override
    public Result<Void> shopStatementWithdrawableGet(@NotNull @ApiParam(value = "提现金额", required = true) @Valid @RequestParam(value = "money", required = true) String money) {
        Long shopId = getShopId();
        Long userId = getUserId();

        try {
            Result<SysUser> result = sysUserApi.getShopkeeper(shopId);
            if(!result.isSuccess()||result.getData()==null) {
                throw new Exception("获取店铺所属用户错误");

            }else if(!Objects.equals(userId,result.getData().getPersonnelId())){
                throw new IllegalArgumentException("店铺所属用户与登录用户不一致");
            }

            statementShopService.withdrawable(StatementUtil.valiPrice(money,EnumUtil.Required.YES),shopId,userId);

            return ResultGenerator.genSuccessResult();

        } catch (Exception e) {
            log.error("店铺提现，shopid--{}--momney--{}",shopId,money, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<StatementDetailVo> shopStatementDetailIdGet(@ApiParam(value = "id",required=true) @PathVariable("id") Long id) {
        Long shopId = getShopId();
        try {
            StatementShop statement = statementShopService.getById(id);
            if(statement==null||!Objects.equals(statement.getShopId(),shopId)){
                return ResultGenerator.genSuccessResult();
            }else{
                AtomicReference<String> voucherPath=new AtomicReference<>();
                AtomicReference<String> voucherNo=new AtomicReference<>();
                List<StatementRecordVo> recordList = new ArrayList<>();
                if(Objects.equals(statement.getType(),StatementType.expenditure.getIndex())){
                    List<StatementShopDetail> detailList = statementShopDetailService.list(new QueryWrapper<StatementShopDetail>().eq("statement_id",statement.getId()));
                    recordList = detailList.stream().peek(record->{
                        if(Objects.equals(record.getStatus(),StatementStatus.END.getIndex())){
                            voucherPath.set(record.getVoucherPath());
                            voucherNo.set(record.getVoucherNo());
                        }
                    }) .map(record->new StatementRecordVo()
                            .date(record.getWorkDate().getTime())
                            .status(record.getStatus())).collect(Collectors.toList());
                }
                StatementDetailVo vo = new StatementDetailVo()
                        .money(statement.getMoney()!=null?NumberUtils.changeF2Y2(statement.getMoney().toString()):"0")
                        .shareMoney(statement.getShareMoney()!=null?NumberUtils.changeF2Y2(statement.getShareMoney().toString()):"0")
                        .summary(statement.getSummary())
                        .type(statement.getType())
                        .isArrival(StatementUtil.getStatus(statement))
                        .date(statement.getTradeDate().getTime())
                        .recordList(recordList)
                        .voucherNo(voucherNo.get())
                        .voucherPath(voucherPath.get())
                        .id(statement.getId());
                return ResultGenerator.genSuccessResult(vo);
            }
        } catch (Exception e) {
            log.error("店铺交易详情，shopId--{}--id--{}",shopId,id, e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }
}
